package com.malty.gateway.filter;

import com.malty.common.ErrorCode;
import com.malty.common.exception.BusinessException;
import com.malty.gateway.config.GatewayContext;
import com.malty.gateway.sign.ApiSignStrategy;
import com.malty.gateway.sign.ApiSignStrategyDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

import static com.malty.gateway.config.constant.GateWayConstant.GATEWAY_CONTEXT;

/**
 * @author malty
 */
@Component
@Slf4j
public class ApiSignCheckFilter implements GlobalFilter, Ordered {
    @Autowired
    private ServerCodecConfigurer codecConfigurer;

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            GatewayContext context = exchange.getAttribute(GATEWAY_CONTEXT);
            return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> {
                ServerWebExchange mutatedExchange = exchange.mutate().request(serverHttpRequest).build();

                ApiSignStrategy apiSignStrategy = ApiSignStrategyDispatcher.selectStrategy(mutatedExchange);

                return apiSignStrategy.checkSign(context.getSecretKey(), mutatedExchange)
                        .onErrorResume(BusinessException.class, e ->
                                unauthorizedResponse(mutatedExchange.getResponse(), e.getMessage()))
                        .then(chain.filter(mutatedExchange));
            });
        }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 2;
    }

    /**
     * 自定义返回 401 错误
     */
    private Mono<Void> unauthorizedResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String body = String.format("{\"code\": %d, \"message\": \"%s\"}", ErrorCode.SIGNATURE_ERROR.getCode(), message);
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
